<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="公司名称">
                <a-input
                  :style="{width: '100%'}"
                  v-model="queryParam.companyName"
                  placeholder="请输入公司名称" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="微信群">
                <a-input
                  :style="{width: '100%'}"
                  v-model="queryParam.wechatName"
                  placeholder="请输入微信群" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="代理商名称">
                <a-input
                  :style="{width: '100%'}"
                  v-model="queryParam.supplierName"
                  placeholder="请输入代理商名称" />
              </a-form-item>
            </a-col>
            <a-col
              :md="3"
              :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="searchSupplier">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => {this.queryParam = {};this.$refs.table.refresh() }">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button
          type="primary"
          icon="plus"
          v-if="save"
          @click="addSupplier">新建</a-button>
      </div>
      <div>
        <s-table
          ref="table"
          size="default"
          rowKey="supplierId"
          :columns="columns"
          :data="loadData"
          :customRow="tableSupplierRow"
          showPagination="auto">
          <span
            slot="serial"
            slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span
            slot="status"
            slot-scope="text">
            <a-badge
              :status="text | statusTypeFilter"
              :text="text | statusFilter" />
          </span>
          <span
            slot="description"
            slot-scope="text">
            <ellipsis
              :length="4"
              tooltip>{{ text }}</ellipsis>
          </span>

          <span
            slot="action"
            slot-scope="text, record">
            <template>
              <a v-if="update" @click="handleEditSupplier(record)">配置</a>
              <a-divider type="vertical" />
              <a v-if="update" @click="handleUpdateSupplier(record)">更新返点</a>
              <a-divider type="vertical" />
              <a v-if="deleteBtn" @click="handleDeleteSupplier(record)">删除</a>
            </template>
          </span>
        </s-table>
      </div>

      <supplier-create-form
        ref="supplierCreatForm"
        :visible="supplierCreateVisible"
        :loading="supplierLoading"
        :prodlist="prodlist"
        @cancel="handleCancel"
        @ok="supplierCreateOK" />
      <supplier-edit-form
        ref="supplierEditForm"
        :visible="supplierEditVisible"
        :loading="supplierLoading"
        :prodlist="prodlist"
        @cancel="handleCancel"
        @ok="supplierEditOK" />
      <supplier-update-form
        ref="supplierUpdateForm"
        :visible="supplierUpdateVisible"
        :loading="supplierLoading"
        :prodlist="prodlist"
        @cancel="handleCancel"
        @ok="supplierUpdateOK" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
// import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import {
  supplierInfo,
  supplierSave,
  supplierUpdate,
  supplierDelete,
  productList,
  getContact, supplierUpdateDiscount
} from '@/api/manage'

import SupplierCreateForm from './modules/SupplierCreateForm'
import SupplierEditForm from './modules/SupplierEditForm'
import SupplierUpdateForm from './modules/SupplierUpdateForm'
import { columns } from './config'
import { message, Modal } from 'ant-design-vue'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    SupplierCreateForm,
    SupplierEditForm,
    SupplierUpdateForm
  },
  data () {
    this.columns = columns
    return {
      // 权限参数
      list: false, // 查
      save: false, // 加
      deleteBtn: false, // 删
      update: false, // 改

      supplierCreateVisible: false,
      supplierEditVisible: false,
      supplierUpdateVisible: false,

      supplierLoading: false,

      custom: undefined,
      contact: undefined,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      prodlist: [],
      contacts: [],
      supplier: undefined,

      contactTabLoading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize }
        const param = Object.assign({}, this.queryParam)
        return (
          this.list &&
          supplierInfo(
            Object.assign({}, param, requestParameters, { productIds: this.queryParam.productIds?.join(',') })
          ).then(res => {
            return Object.assign({}, res, {
              totalCount: res.total,
              pageNo: parameter.pageNo,
              pageSize: parameter.pageSize
            })
          })
        )
      },
      // staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null
    }
  },
  created () {
    // 点击查看
    this.list =
      isInMenu(this.menu, 'ROLE_but:supplier:list') &&
      isInMenu(this.menu, 'ROLE_but:supplier:info') &&
      isInMenu(this.menu, 'ROLE_but:contact:info') &&
      isInMenu(this.menu, 'ROLE_but:contact:list')
    // 增加
    this.save =
      isInMenu(this.menu, 'ROLE_but:supplier:save') &&
      isInMenu(this.menu, 'ROLE_but:contact:save') &&
      isInMenu(this.menu, 'ROLE_but:product:select')
    // 改
    this.update =
      isInMenu(this.menu, 'ROLE_but:supplier:update') &&
      isInMenu(this.menu, 'ROLE_but:contact:update') &&
      isInMenu(this.menu, 'ROLE_but:product:select')
    // 删除
    this.deleteBtn = isInMenu(this.menu, 'ROLE_but:supplier:delete') && isInMenu(this.menu, 'ROLE_but:contact:delete')
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows,
        onChange: this.onSelectChange
      }
    }
  },
  mounted () {
    isInMenu(this.menu, 'ROLE_but:product:select') &&
      productList().then(res => {
        this.prodlist = res.data
        // console.log(this.prodlist, 'this.prodlist')
      })
  },
  methods: {
    handleDeleteSupplier (record) {
      Modal.confirm({
        title: '删除供应商',
        content: '删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          this.loading = true
          supplierDelete({ supplierId: record.supplierId }).then(() => {
            message.success('删除成功')
            this.$refs.table.refresh()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    // add 创新新的表格
    searchSupplier () {
      // const param = Object.assign({}, this.queryParam)
      this.$refs.table.refresh()
    },
    addSupplier () {
      this.custom = null
      this.supplierCreateVisible = true
    },
    // edit 展示表格 nextTick 并赋值
    handleEditSupplier (record) {
      this.custom = { ...record }
      this.supplierEditVisible = true
      const form = this.$refs.supplierEditForm.form
      this.$nextTick(() => {
        const _custom = Object.assign({}, this.custom)
        form.setFieldsValue(_custom)
      })
    },
    // update 展示表格 nextTick 并赋值
    handleUpdateSupplier (record) {
      this.custom = { ...record }
      this.supplierUpdateVisible = true
      const form = this.$refs.supplierUpdateForm.form
      this.$nextTick(() => {
        const _custom = Object.assign({}, this.custom)
        form.setFieldsValue(_custom)
      })
    },
    // 通过 ref 获取表格实例
    supplierCreateOK () {
      const form = this.$refs.supplierCreatForm.form
      this.supplierLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const param = Object.assign({}, values)
          supplierSave(param).then(res => {
            if (res.code === 0) {
              this.supplierCreateVisible = false
              this.$refs.table.refresh()
              this.supplierLoading = false
              this.$message.info('新增成功')
              form.resetFields()
            }
          }).finally(() => { this.supplierLoading = false })
        }
        this.supplierLoading = false
      })
    },
    supplierEditOK () {
      const form = this.$refs.supplierEditForm.form
      form.validateFields((errors, values) => {
        if (!errors) {
          const param = Object.assign({}, values, { supplierId: this.custom.supplierId })
          supplierUpdate(param).then(() => {
            this.supplierLoading = false
            this.supplierEditVisible = false
            this.$message.info('配置修改成功')
            form.resetFields()
            this.$refs.table.refresh()
          }).finally(() => { this.supplierLoading = false })
        }
      })
    },
    supplierUpdateOK () {
      const form = this.$refs.supplierUpdateForm.form
      form.validateFields((errors, values) => {
        if (!errors) {
          const param = Object.assign({}, values)
          supplierUpdateDiscount(param).then(res => {
            if (res.code === 0) {
              this.supplierUpdateVisible = false
              this.$refs.table.refresh()
              this.supplierLoading = false
              this.$message.info('更新成功')
              form.resetFields()
            }
          }).finally(() => { this.supplierLoading = false })
        }
      })
    },
    handleCancel () {
      this.supplierCreateVisible = false
      this.supplierEditVisible = false
      this.supplierUpdateVisible = false
      this.$refs.supplierCreatForm.form.resetFields()
      this.$refs.supplierEditForm.form.resetFields()
      this.$refs.supplierUpdateForm.form.resetFields()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      // todo supplierId selectedRows array[supplierId]
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    tableSupplierRow (record, index) {
      return {
                style: {
          'background-color': record.supplierId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.supplier = record
            this.physicalSurveyCurrRowId = record.supplierId
            if (this.list) {
              this.contactTabLoading = true
              getContact({ relationId: record.supplierId, type: 2, page: 1, limit: 100 }).then(res => {
                this.contacts = res.data
                this.contactTabLoading = false
              })
            }
          }
        }
      }
    }
  }
}
</script>
